package com.prs.crm.action.oa;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.annotation.Clew;
import com.prs.crm.context.AppContext;
import com.prs.crm.context.Constrains;
import com.prs.crm.context.FileUtil;
import com.prs.crm.context.ToolKits;
import com.prs.crm.domain.doc.DocLevel;
import com.prs.crm.domain.doc.DocType;
import com.prs.crm.domain.doc.Document;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.oa.Notice;
import com.prs.crm.domain.oa.OaTask;
import com.prs.crm.domain.oa.OaTaskAudit;
import com.prs.crm.domain.oa.OaTaskCritique;
import com.prs.crm.domain.oa.OaTaskKeyWord;
import com.prs.crm.domain.oa.OaTaskLog;
import com.prs.crm.domain.oa.OaTaskSource;
import com.prs.crm.domain.oa.OaTaskSubmit;
import com.prs.crm.domain.oa.OaTaskType;
import com.prs.crm.domain.sys.Code;
import com.prs.crm.domain.sys.CodeCommon;
import com.prs.crm.exception.InValidException;
import com.prs.crm.report.ReportUtils;
import com.prs.crm.service.doc.DocLevelService;
import com.prs.crm.service.doc.DocumentService;
import com.prs.crm.service.oa.NoticeService;
import com.prs.crm.service.oa.OaTaskAuditService;
import com.prs.crm.service.oa.OaTaskCritiqueService;
import com.prs.crm.service.oa.OaTaskKeyWordService;
import com.prs.crm.service.oa.OaTaskLogService;
import com.prs.crm.service.oa.OaTaskService;
import com.prs.crm.service.oa.OaTaskSourceService;
import com.prs.crm.service.oa.OaTaskSubmitService;
import com.prs.crm.service.oa.OaTaskTypeService;
import com.prs.crm.service.sys.CodeCommonService;
import com.prs.crm.service.sys.CodeService;

public class OaTaskAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private static final String key = "com.prs.crm.oa.taskDockey";
	private OaTaskKeyWord oaTaskKeyWord;
	private OaTask oaTask;
	private OaTaskService oaTaskService;
	private PaginationSupport pagination;
	private Integer[] ids;
	private Integer[] docIds;
	private OaTaskSubmit oaTaskSubmit;
	private OaTaskAudit oaTaskAudit;
	private OaTaskCritique oaTaskCritique;
	private OaTaskLog oaTaskLog;
	private Document document;

	private OaTaskKeyWordService oaTaskKeyWordService;
	private DocumentService documentService;
	private OaTaskTypeService oaTaskTypeService;
	private OaTaskSourceService oaTaskSourceService;
	private OaTaskSubmitService oaTaskSubmitService;
	private OaTaskAuditService oaTaskAuditService;
	private OaTaskCritiqueService oaTaskCritiqueService;
	private DocLevelService docLevelService;
	private NoticeService noticeService;
	private OaTaskLogService oaTaskLogService;
	private boolean submited;

	private File upload;
	private String uploadFileName;
	private File selectDoc;
	private String selectDocFileName;

	private List<OaTaskType> oaTaskTypes;
	private List<OaTaskSource> oaTaskSources;
	private Collection<OaTask> ownChildTasks;
	private Collection<OaTaskLog> oaTaskLogs;
	private Collection<DocLevel> docLevels;
	private Collection<Document> relatDocs;

	private boolean existStor;
	private int submitState = 1;

	private String principals;
	private String copyToPersons;
	private String levelType;

	private String[] names;
	private String[] codes;
	private DocType[] types;
	private String[] files;
	private DocLevel[] levels;
	private String[] keyWords;
	private String[] keyNames;

	private CodeCommon codeCommon;
	private CodeCommonService codeCommonService;
	private String Encode;
	private Code code;
	private CodeService codeService;

	private Collection<CodeCommon> codelist;

	@Action("listTask")
	public String execute() {

		return SUCCESS;
	}

	@Action("listTaskByLevel")
	public String listTaskByLevel() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				OaTask.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		criteria.add(Restrictions.isNull("upTask"));
		if (levelType != null) {
			if (!"all".equals(levelType)) {
				levelType = levelType.split(",")[0];
				if (ToolKits.isInteger(levelType)) {
					criteria.createAlias("type", "tp");
					criteria.add(Restrictions.eq("tp.id", Integer
							.parseInt(levelType)));
				} else {
					levelType = ReportUtils.URLDecode(levelType);
					criteria.add(Restrictions.eq("level", levelType));
				}
			}
		}
		this.setPagination(this.getOaTaskService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listExecuteTask")
	public String listExecuteTask() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				OaTaskSubmit.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		Person person = AppContext.getAccountContext().currentUser();
		// criteria.createAlias("principals", "p").add(Restrictions.eq("p.id",
		// person.getId()));
		criteria.add(Restrictions.or(Restrictions.eq("state",
				Constrains.TASK_EXECUTE), Restrictions.eq("state",
				Constrains.TASK_NOTPASS)));
		criteria.add(Restrictions.eq("exePerson", person));
		this.setPagination(this.getOaTaskSubmitService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listCritiqueTask")
	public String listCritiqueTask() {
		return SUCCESS;
	}

	@Action("listCritiqueTaskByLevel")
	public String listCritiqueTaskByLevel() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				OaTask.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		Person person = AppContext.getAccountContext().currentUser();
		criteria.add(Restrictions.ne("state", Constrains.TASK_PASS));
		criteria.createAlias("copyToPersons", "c").add(
				Restrictions.eq("c.id", person.getId()));
		Date start = null;
		Date end = null;
		if (levelType != null) {
			if (!"all".equals(levelType)) {
				levelType = levelType.split(",")[0];
				if (ToolKits.isInteger(levelType)) {
					criteria.createAlias("type", "tp");
					criteria.add(Restrictions.eq("tp.id", Integer
							.parseInt(levelType)));
				} else {
					if (levelType.indexOf("$") != -1) {
						start = ReportUtils.convertToDate(levelType.replace(
								"$", "").trim());
						end = ReportUtils.convertToDate(String
								.valueOf(Integer.parseInt(levelType.replace(
										"$", "").trim()) + 1));
					} else if (levelType.indexOf("-") != -1) {
						start = ReportUtils.convertToDateFrom(levelType);
						Calendar cal = Calendar.getInstance();
						cal.setTime(start);
						String s = String
								.valueOf(cal.get(Calendar.MONTH) + 2 > 12 ? "12"
										: "" + (cal.get(Calendar.MONTH) + 2));
						if (cal.get(Calendar.MONTH) + 2 > 12)
							end = ReportUtils.convertToDate(String.valueOf(cal
									.get(Calendar.YEAR)), s, "31");
						else
							end = ReportUtils.convertToDate(String.valueOf(cal
									.get(Calendar.YEAR)), s);
					} else {
						levelType = ReportUtils.URLDecode(levelType);
						criteria.add(Restrictions.eq("level", levelType));
					}
				}
			}
		}
		if (start != null && end != null) {
			criteria.add(Restrictions.ge("endTime", start));
			criteria.add(Restrictions.lt("endTime", end));
		}

		this.setPagination(this.getOaTaskService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listAuditTask")
	public String listAuditTask() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				OaTaskSubmit.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		Person person = AppContext.getAccountContext().currentUser();
		criteria.add(Restrictions.eq("state", Constrains.TASK_AUDITING));
		// criteria.createAlias("task", "t").add(Restrictions.eq("t.recorder",
		// person));
		criteria.add(Restrictions.eq("exePerson", person));
		this.setPagination(this.getOaTaskSubmitService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listExeFinishTask")
	public String listExeFinishTask() {
		return SUCCESS;
	}

	@Action("listExeFinishTaskByLevel")
	public String listExeFinishTaskByLevel() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				OaTaskSubmit.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		Person person = AppContext.getAccountContext().currentUser();
		criteria.add(Restrictions.eq("state", Constrains.TASK_PASS));
		criteria.add(Restrictions.eq("exePerson", person));
		Date start = null;
		Date end = null;
		if (levelType != null) {
			if (!"all".equals(levelType)) {
				criteria.createAlias("task", "t");
				levelType = levelType.split(",")[0];
				if (ToolKits.isInteger(levelType)) {
					criteria.createAlias("t.type", "tp");
					criteria.add(Restrictions.eq("tp.id", Integer
							.parseInt(levelType)));
				} else {
					if (levelType.indexOf("$") != -1) {
						start = ReportUtils.convertToDate(levelType.replace(
								"$", "").trim());
						end = ReportUtils.convertToDate(String
								.valueOf(Integer.parseInt(levelType.replace(
										"$", "").trim()) + 1));
					} else if (levelType.indexOf("-") != -1) {
						start = ReportUtils.convertToDateFrom(levelType);
						Calendar cal = Calendar.getInstance();
						cal.setTime(start);
						String s = String
								.valueOf(cal.get(Calendar.MONTH) + 2 > 12 ? "12"
										: "" + (cal.get(Calendar.MONTH) + 2));
						if (cal.get(Calendar.MONTH) + 2 > 12)
							end = ReportUtils.convertToDate(String.valueOf(cal
									.get(Calendar.YEAR)), s, "31");
						else
							end = ReportUtils.convertToDate(String.valueOf(cal
									.get(Calendar.YEAR)), s);
					} else {
						levelType = ReportUtils.URLDecode(levelType);
						criteria.add(Restrictions.eq("t.level", levelType));
					}
				}
			}
		}
		if (start != null && end != null) {
			criteria.add(Restrictions.ge("t.endTime", start));
			criteria.add(Restrictions.lt("t.endTime", end));
		}
		this.setPagination(this.getOaTaskSubmitService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listAuditFinishTask")
	public String listAuditFinishTask() {
		return SUCCESS;
	}

	@Action("listAuditFinishTaskByLevel")
	public String listAuditFinishTaskByLevel() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				OaTaskSubmit.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		Person person = AppContext.getAccountContext().currentUser();
		criteria.add(Restrictions.eq("state", Constrains.TASK_PASS));
		criteria.add(Restrictions.eq("recorder", person));
		// criteria.add(Restrictions.eq("exePerson", person));
		Date start = null;
		Date end = null;
		if (levelType != null) {
			if (!"all".equals(levelType)) {
				criteria.createAlias("task", "t");
				levelType = levelType.split(",")[0];
				if (ToolKits.isInteger(levelType)) {
					criteria.createAlias("t.type", "tp");
					criteria.add(Restrictions.eq("tp.id", Integer
							.parseInt(levelType)));
				} else {
					if (levelType.indexOf("$") != -1) {
						start = ReportUtils.convertToDate(levelType.replace(
								"$", "").trim());
						end = ReportUtils.convertToDate(String
								.valueOf(Integer.parseInt(levelType.replace(
										"$", "").trim()) + 1));
					} else if (levelType.indexOf("-") != -1) {
						start = ReportUtils.convertToDateFrom(levelType);
						Calendar cal = Calendar.getInstance();
						cal.setTime(start);
						String s = String
								.valueOf(cal.get(Calendar.MONTH) + 2 > 12 ? "12"
										: "" + (cal.get(Calendar.MONTH) + 2));
						if (cal.get(Calendar.MONTH) + 2 > 12)
							end = ReportUtils.convertToDate(String.valueOf(cal
									.get(Calendar.YEAR)), s, "31");
						else
							end = ReportUtils.convertToDate(String.valueOf(cal
									.get(Calendar.YEAR)), s);
					} else {
						levelType = ReportUtils.URLDecode(levelType);
						criteria.add(Restrictions.eq("t.level", levelType));
					}
				}
			}
		}
		if (start != null && end != null) {
			criteria.add(Restrictions.ge("t.endTime", start));
			criteria.add(Restrictions.lt("t.endTime", end));
		}
		this.setPagination(this.getOaTaskSubmitService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listCritiqueFinishTask")
	public String listCritiqueFinishTask() {
		return SUCCESS;
	}

	@Action("listCritiqueFinishTaskByLevel")
	public String listCritiqueFinishTaskByLevel() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				OaTask.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		Person person = AppContext.getAccountContext().currentUser();
		criteria.add(Restrictions.eq("state", Constrains.TASK_PASS));
		criteria.createAlias("copyToPersons", "c").add(
				Restrictions.eq("c.id", person.getId()));
		Date start = null;
		Date end = null;
		if (levelType != null) {
			if (!"all".equals(levelType)) {
				levelType = levelType.split(",")[0];
				if (ToolKits.isInteger(levelType)) {
					criteria.createAlias("type", "tp");
					criteria.add(Restrictions.eq("tp.id", Integer
							.parseInt(levelType)));
				} else {
					if (levelType.indexOf("$") != -1) {
						start = ReportUtils.convertToDate(levelType.replace(
								"$", "").trim());
						end = ReportUtils.convertToDate(String
								.valueOf(Integer.parseInt(levelType.replace(
										"$", "").trim()) + 1));
					} else if (levelType.indexOf("-") != -1) {
						start = ReportUtils.convertToDateFrom(levelType);
						Calendar cal = Calendar.getInstance();
						cal.setTime(start);
						String s = String
								.valueOf(cal.get(Calendar.MONTH) + 2 > 12 ? "12"
										: "" + (cal.get(Calendar.MONTH) + 2));
						if (cal.get(Calendar.MONTH) + 2 > 12)
							end = ReportUtils.convertToDate(String.valueOf(cal
									.get(Calendar.YEAR)), s, "31");
						else
							end = ReportUtils.convertToDate(String.valueOf(cal
									.get(Calendar.YEAR)), s);
					} else {
						levelType = ReportUtils.URLDecode(levelType);
						criteria.add(Restrictions.eq("level", levelType));
					}
				}
			}
		}
		if (start != null && end != null) {
			criteria.add(Restrictions.ge("endTime", start));
			criteria.add(Restrictions.lt("endTime", end));
		}
		this.setPagination(this.getOaTaskService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("editCritiqueTask")
	public String editCritiqueTask() {
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "submitCritique", results = { @Result(name = "success", type = "redirect", location = "listCritiqueTask") })
	public String submitCritique() {
		this.setPrompt("提交任务点评成功");
		oaTaskCritique.setTask(oaTask);
		this.getOaTaskCritiqueService().saveOaTaskCritique(oaTaskCritique,
				upload, uploadFileName);
		return SUCCESS;
	}

	@Action("viewCritiqueTask")
	public String viewCritiqueTask() {
		return SUCCESS;
	}

	@Action("editAuditTask")
	public String editAuditTask() {
		return SUCCESS;
	}

	@Action("executeTask")
	public String executeTask() {
		this.setOwnChildTasks(this.getOaTaskService().getChildTask(
				oaTaskSubmit.getTask(),
				AppContext.getAccountContext().currentUser()));
		this.setOaTaskLogs(this.getOaTaskLogService()
				.getOaTaskLog(oaTaskSubmit));
		return SUCCESS;
	}

	@Action("editTaskLog")
	public String editTaskLog() {
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "submitTaskLog", results = { @Result(name = "success", type = "redirect", location = "executeTask?oaTaskSubmit=${oaTaskSubmit.id}") })
	public String submitTaskLog() {
		oaTaskLog.setOaTaskSubmit(oaTaskSubmit);
		oaTaskLog.setState(Constrains.TASK_AUDITING);
		this.getOaTaskLogService().submitTaskLog(oaTaskLog, upload,
				uploadFileName);
		this.setPrompt("提交任务日志成功!");
		return SUCCESS;
	}

	@Action("listTaskLog")
	public String listTaskLog() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				OaTaskLog.class);
		criteria.createAlias("oaTaskSubmit", "s");
		criteria.add(Restrictions.eq("s.recorder", AppContext
				.getAccountContext().currentUser()));
		criteria.add(Restrictions.eq("state", Constrains.TASK_AUDITING));
		criteria.addOrder(Order.desc("recordTime"));
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getOaTaskLogService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("verifyTaskLog")
	public String verifyTaskLog() {
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "passTaskLog", results = { @Result(name = "success", type = "redirect", location = "listTaskLog") })
	public String passTaskLog() {
		oaTaskLog.setState(Constrains.TASK_PASS);
		this.getOaTaskLogService().save(oaTaskLog);
		this.setPrompt("工作量确认通过");
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "rebutTaskLog", results = { @Result(name = "success", type = "redirect", location = "listTaskLog") })
	public String rebutTaskLog() {
		oaTaskLog.setState(Constrains.TASK_NOTPASS);
		this.getOaTaskLogService().save(oaTaskLog);
		this.setPrompt("工作量确认打回");
		return SUCCESS;
	}

	@Action("viewTaskLog")
	public String viewTaskLog() {
		return SUCCESS;
	}

	@Action(value = "removeTaskLog", results = {
			@Result(name = "success", type = "redirect", location = "executeTask?oaTaskSubmit=${oaTaskSubmit.id}"),
			@Result(name = "error", type = "chain", location = "executeTask") })
	public String removeTaskLog() {
		if (ids == null) {
			this.addActionError("请选择要删除的工作日志!");
			return ERROR;
		}
		for (Integer id : ids) {
			OaTaskLog log = this.getOaTaskLogService().get(id);
			if (!log.getState().equals(Constrains.TASK_AUDITING)) {
				this.addActionError("工作日志已回复，不能删除!");
				return ERROR;
			}
		}
		this.getOaTaskLogService().batchRemove(ids);
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "submitTask", results = {
			@Result(name = "success", type = "redirect", location = "listExecuteTask"),
			@Result(name = "error", type = "chain", location = "executeTask") })
	public String submitTask() {
		Collection<OaTask> oaTasks = this.getOaTaskService().getChildTask(
				oaTaskSubmit.getTask(),
				AppContext.getAccountContext().currentUser());
		for (OaTask oaTask : oaTasks) {
			if (!oaTask.getState().equals(Constrains.TASK_PASS)) {
				this.addActionError("还有子任务未完成，请等待子任务完成!");
				return ERROR;
			}
		}
		oaTaskSubmit.setState(Constrains.TASK_AUDITING);
		this.getOaTaskSubmitService().saveOaTaskSubmit(oaTaskSubmit, upload,
				uploadFileName);

		String msg = oaTaskSubmit.getExePerson().getResume().getName()
				+ "已提交工作任务:" + oaTaskSubmit.getTask().getTitle() + "，请审核";
		Notice notice = new Notice();
		notice.setTitle("工作任务审核");
		notice.setContent(msg);

		this.getNoticeService().sendNotice(notice,
				oaTaskSubmit.getTask().getRecorder());

		this.setPrompt("提交工作任务成功");
		return SUCCESS;
	}

	@Action("editTask")
	public String editTask() {
		this.prepare();
		if (!existStor) {
			this.getStorage().remove(key);
			if (oaTask != null) {
				relatDocs = new ArrayList<Document>();// document Collecction
				this.getStorage().save(key, relatDocs);
				if (oaTask.getDocs() != null) {
					relatDocs.addAll(oaTask.getDocs());
				}
			}
		}
		if (this.getStorDocs() == null) {
			relatDocs = new ArrayList<Document>();
			this.getStorage().save(key, relatDocs);
		}
		return SUCCESS;
	}

	@Action("editWorkTaskCreat")
	public String editWorkTaskCreat() {
		this.prepare();
		if (!existStor) {
			this.getStorage().remove(key);
			if (oaTask != null) {
				relatDocs = new ArrayList<Document>();
				this.getStorage().save(key, relatDocs);
				if (oaTask.getDocs() != null) {
					relatDocs.addAll(oaTask.getDocs());
				}
			}
			this.codelist = this.getCodeCommonService()
					.getCodeCommonByCodeType("文档");

		}
		if (this.getStorDocs() == null) {
			relatDocs = new ArrayList<Document>();
			this.getStorage().save(key, relatDocs);
		}
		return SUCCESS;
	}

	@Action("editNewTask")
	public String editNewTask() {
		this.prepare();
		if (!existStor) {
			this.getStorage().remove(key);
			if (oaTask != null) {
				relatDocs = new ArrayList<Document>();
				this.getStorage().save(key, relatDocs);
				if (oaTask.getDocs() != null) {
					relatDocs.addAll(oaTask.getDocs());
				}
			}
		}
		if (this.getStorDocs() == null) {
			relatDocs = new ArrayList<Document>();
			this.getStorage().save(key, relatDocs);
		}
		this.codelist = this.getCodeCommonService().getCodeCommonByCodeType(
				"文档");
		return SUCCESS;
	}

	@Action("createChildTask")
	public String createChildTask() {
		this.prepare();
		if (!existStor) {
			this.getStorage().remove(key);
			if (oaTask != null) {
				relatDocs = new ArrayList<Document>();
				this.getStorage().save(key, relatDocs);
				if (oaTask.getDocs() != null) {
					relatDocs.addAll(oaTask.getDocs());
				}
			}
		}
		if (this.getStorDocs() == null) {
			relatDocs = new ArrayList<Document>();
			this.getStorage().save(key, relatDocs);
		}
		return SUCCESS;
	}

	// -----------------------------------------------------------------------------------------------创建文档
	@Action(value = "creatTaskWork", results = { @Result(name = "success", type = "json", params = {
			"root", "mapValidateStockAlert" }) })
	public String validateStockAlert1() {

		return SUCCESS;
	}

	private String appendDocument() {
		this.setExistStor(true);
		if (document.getName() == null || document.getName().trim().equals("")) {
			this.addActionError("请正确填写文档名称");
			return ERROR;
		}
		if (document.getDocumentcode() == null
				|| document.getDocumentcode().trim().equals("")) {
			this.addActionError("请正确填写文档编码");
			return ERROR;
		}
		if (document.getType() == null) {
			this.addActionError("请选择文档类型");
			return ERROR;
		}
		if (selectDoc == null) {
			this.addActionError("请选择文档");
			return ERROR;
		}
		if (oaTask.getDocs() == null) {
			oaTask.setDocs(new HashSet<Document>());
		}

		relatDocs = this.getStorDocs();
		if (relatDocs == null) {
			relatDocs = new ArrayList<Document>();
			this.getStorage().save(key, relatDocs);
		}

		document.setId(relatDocs.size());
		document.setAttach(FileUtil.getInstance().createAttach(selectDoc,
				selectDoc.getName()));
		document.getType().getName();
		document.getLevel().getName();
		document.getCode().getCodeValue();

		oaTask.addDocs(document);

		relatDocs.add(document);

		submitState = 0;
		return SUCCESS;
	}

	private String removeDocument() {
		this.setExistStor(true);
		if (docIds == null) {
			this.addActionError("请选择要删除的文档");
			return ERROR;
		}
		if (this.getStorDocs() != null) {
			relatDocs = this.getStorDocs();
			for (Integer id : docIds) {
				for (Document doc : relatDocs) {
					if (doc.getId() == id) {
						relatDocs.remove(doc);
						break;
					}
				}
			}
		}

		return SUCCESS;
	}

	@Action(value = "appendTaskDocument", results = {
			@Result(name = "success", type = "chain", location = "editTask"),
			@Result(name = "error", type = "chain", location = "editTask") })
	public String appendTaskDocument() {
		this.submited = true;
		this.appendDocument();
		return SUCCESS;
	}

	@Action(value = "appendChildTaskDocument", results = {
			@Result(name = "success", type = "chain", location = "createChildTask"),
			@Result(name = "error", type = "chain", location = "createChildTask") })
	public String appendChildTaskDocument() {
		return this.appendDocument();
	}

	@Action(value = "removeTaskDocument", results = {
			@Result(name = "success", type = "chain", location = "editTask"),
			@Result(name = "error", type = "chain", location = "editTask") })
	public String removeTaskDocument() {
		return this.removeDocument();
	}

	@Action(value = "removeChildTaskDocument", results = {
			@Result(name = "success", type = "chain", location = "createChildTask"),
			@Result(name = "error", type = "chain", location = "createChildTask") })
	public String removeChildTaskDocument() {
		return this.removeDocument();
	}

	@Clew(results = { "success" })
	@Action(value = "saveNewTask", results = {
			@Result(name = "success", type = "redirect", location = "editNewTask"),
			@Result(name = "error", type = "chain", location = "editNewTask") })
	public String saveNewTask() {
		this.setExistStor(true);
		if (document.getName() == null || document.getName().trim().equals("")) {
			this.addActionError("请正确填写文档名称");
			return ERROR;
		}
		if (document.getDocumentcode() == null
				|| document.getDocumentcode().trim().equals("")) {
			this.addActionError("请正确填写文档编码");
			return ERROR;
		}
		if (document.getType() == null) {
			this.addActionError("请选择文档类型");
			return ERROR;
		}
		

		if ("n".equals(Encode)) {
			Code codes = new Code();
			codes.setCodeValue(document.getDocumentcode());
			codes.setEntityName(this.getClass().getName());
			codes.setCodeType("手动编码");
			codes.setCodeMolde("文档");
			this.getCodeService().save(codes);
			document.setCode(codes);

		} else {
			CodeCommon Vob = this.getCodeCommonService().getVobject(
					codeCommon.getId());
			Code codes = new Code();
			codes.setEntityName(this.getClass().getName());
			codes.setCodeValue(document.getDocumentcode());
			Vob.setNumBackUp(Increase(Vob.getNumBackUp()));
			this.codeCommonService.saveOrUpdate(Vob);
			codes.setCodeType(Vob.getCodePlan());
			codes.setCodeMolde("文档");
			this.getCodeService().save(codes);
			document.setCode(codes);
		}
		if (selectDoc != null) {
			document.setAttach(FileUtil.getInstance().createAttach(selectDoc,
					selectDoc.getName()));
		}
		document.setKeyWord(document.getKeyWord().replace(",", " "));
		this.setPrompt("创建工作任务成功");
		this.getDocumentService().save(document);
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "saveTask", results = {
			@Result(name = "success", type = "redirect", location = "editTask"),
			@Result(name = "error", type = "chain", location = "editTask") })
	public String save() {
		if (oaTask.getTitle() == null || "".equals(oaTask.getTitle().trim())) {
			addActionError("任务名称不能为空");
			return ERROR;
		}
		if (oaTask.getType() == null) {
			addActionError("类型不能为空");
			return ERROR;
		}
		if (oaTask.getBeginTime() == null) {
			addActionError("开始时间不能为空");
			return ERROR;
		}
		if (oaTask.getEndTime() == null) {
			addActionError("结束时间不能为空");
			return ERROR;
		}
		if (principals == null || "".equals(principals.trim())) {
			addActionError("执行人不能为空");
			return ERROR;
		}
		if (copyToPersons == null || "".equals(copyToPersons.trim())) {
			addActionError("抄送人不能为空");
			return ERROR;
		}
		if (oaTask.getLevel() == null) {
			addActionError("等级不能为空");
			return ERROR;
		}
		if (oaTask.getSource() == null) {
			addActionError("来源不能为空");
			return ERROR;
		}
		if (names == null) {
			addActionError("任务文档不能为空");
			return ERROR;
		}
		this.setPrompt("创建工作任务成功");
		this.setExistStor(true);
		relatDocs = this.getStorDocs();

		oaTask.setState(Constrains.TASK_EXECUTE);
		this.getOaTaskService().saveTask(oaTask, upload, uploadFileName,
				principals, copyToPersons);

		for (int i = 0; i < names.length; i++) {
			Document od = new Document();
			od.setName(names[i]);
			od.setDocumentcode(codes[i]);
			od.setLevel(levels[i]);
			od.setType(types[i]);
			String keyN = keyNames[i].replaceAll(",", " ");
			od.setKeyWord(keyN);
			File StringToFile = new File(files[i]);
			od.setAttach(FileUtil.getInstance().createAttach(StringToFile,
					StringToFile.getName()));
			relatDocs.add(od);
		}
		System.out.println("relatDocs OaTask=" + relatDocs.size());
		List<Document> rlist = (List<Document>) relatDocs;
		for (int o = 0; o < rlist.size(); o++) {
			Document doc = rlist.get(o);
			String keyW[] = keyWords[o].split(",");
			for (int k = 0; k < keyW.length; k++) {
				OaTaskKeyWord Ootkw = this.getOaTaskKeyWordService()
						.getOaTaskKeyWord(Integer.parseInt(keyW[k]));
				System.out.println("进入");
				doc.getOaTaskKeyWord().add(Ootkw);
			}
			doc.setId(null);
			doc.setOaTask(oaTask);

			this.getDocumentService().submitDocument(doc);

		}
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "passTask", results = { @Result(name = "success", type = "redirect", location = "listAuditTask") })
	public String passTask() {
		oaTaskSubmit.setState(Constrains.TASK_PASS);
		this.getOaTaskSubmitService().save(oaTaskSubmit);

		oaTaskAudit.setOaTaskSubmit(oaTaskSubmit);
		oaTaskAudit.setState(Constrains.TASK_PASS);
		this.getOaTaskAuditService().saveOaTaskAudit(oaTaskAudit, upload,
				uploadFileName);

		boolean flag = true;
		Collection<OaTaskSubmit> oaTaskSubmits = this.getOaTaskSubmitService()
				.getOaTaskSubmitByTask(oaTaskSubmit.getTask());
		for (OaTaskSubmit oaTaskSubmit : oaTaskSubmits) {
			if (!oaTaskSubmit.getState().equals(Constrains.TASK_PASS)) {
				flag = false;
				break;
			}
		}
		if (flag) {
			oaTaskSubmit.getTask().setState(Constrains.TASK_PASS);
			this.getOaTaskService().save(oaTaskSubmit.getTask());
		}

		String msg = "您提交的工作任务：" + oaTaskSubmit.getTask().getTitle() + "已审核通过！";
		Notice notice = new Notice();
		notice.setTitle("工作任务审核通过");
		notice.setContent(msg);

		this.getNoticeService().sendNotice(notice, oaTaskSubmit.getExePerson());

		this.setPrompt("工作任务审核通过");
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "rebutTask", results = { @Result(name = "success", type = "redirect", location = "listAuditTask") })
	public String rebutTask() {
		this.setPrompt("工作任务审核打回");

		oaTaskSubmit.setState(Constrains.TASK_NOTPASS);
		this.getOaTaskSubmitService().save(oaTaskSubmit);

		oaTaskAudit.setOaTaskSubmit(oaTaskSubmit);
		oaTaskAudit.setState(Constrains.TASK_NOTPASS);
		this.getOaTaskAuditService().saveOaTaskAudit(oaTaskAudit, upload,
				uploadFileName);

		String msg = "您提交的工作任务：" + oaTaskSubmit.getTask().getTitle()
				+ "已被打回，请检查！";
		Notice notice = new Notice();
		notice.setTitle("工作任务审核打回");
		notice.setContent(msg);

		this.getNoticeService().sendNotice(notice, oaTaskSubmit.getExePerson());
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "submitChildTask", results = {
			@Result(name = "success", type = "redirect", location = "listExecuteTask"),
			@Result(name = "error", type = "chain", location = "createChildTask") })
	public String submitChildTask() {
		try {
			this.setExistStor(true);
			relatDocs = this.getStorDocs();
			if (oaTask.getBeginTime().compareTo(
					oaTaskSubmit.getTask().getBeginTime()) < 0
					|| oaTask.getEndTime().compareTo(
							oaTaskSubmit.getTask().getEndTime()) > 0) {
				this.addActionError("子任务的开始时间不得早于父任务的开始时间，结束时间不得晚于父任务的结束时间");
				return ERROR;
			}
			oaTask.setUpTask(oaTaskSubmit.getTask());
			oaTask.setState(Constrains.TASK_EXECUTE);
			this.getOaTaskService().saveTask(oaTask, upload, uploadFileName,
					principals, copyToPersons);

			if (relatDocs != null) {
				for (Document doc : relatDocs) {
					File file = new File(doc.getAttach().getPath());
					String fileName = doc.getAttach().getName();
					doc.setId(null);
					doc.setOaTask(oaTask);
					this.getDocumentService().submitDocument(doc);
				}
				relatDocs.clear();
			}

			this.setPrompt("创建子任务成功");
			return SUCCESS;
		} catch (InValidException e) {
			// TODO: handle exception
			this.addActionError(e.getMessage());
			return ERROR;
		}
	}

	@Action(value = "removeTask", results = {
			@Result(name = "success", type = "redirect", location = "listTask"),
			@Result(name = "error", type = "chain", location = "listTask") })
	public String remove() {
		if (ids == null) {
			this.addActionError("请选择要删除的工作任务");
			return ERROR;
		}
		if (oaTask.getTasks().size() != 0) {
			this.addActionError("还有子任务存在，此任务不能删除");
			return ERROR;
		}
		this.getOaTaskService().batchRemove(ids);
		return SUCCESS;
	}

	@Action("viewTask")
	public String view() {
		copyToPersons = "";
		Iterator<Person> iter = oaTask.getCopyToPersons().iterator();
		while (iter.hasNext()) {
			copyToPersons += iter.next().getResume().getName() + " , ";
		}
		return SUCCESS;
	}

	@Action("viewTaskSubmit")
	public String viewTaskSubmit() {
		this.setOaTaskLogs(this.getOaTaskLogService()
				.getOaTaskLog(oaTaskSubmit));
		return SUCCESS;
	}

	@Action("viewTaskAudit")
	public String viewTaskAudit() {
		return SUCCESS;
	}

	private void prepare() {
		oaTaskTypes = this.getOaTaskTypeService().getAllTaskType();
		oaTaskSources = this.getOaTaskSourceService().getAllTaskSource();
		docLevels = this.getDocLevelService().getAllDocLevel();
	}

	@Action("editTaskDoc")
	public String editTaskDoc() {
		this.setDocLevels(this.getDocLevelService().getAllDocLevel());
		return SUCCESS;
	}

	@Action(value = "submitTaskDoc", results = {
			@Result(name = "success", type = "redirect", location = ""),
			@Result(name = "error", type = "chain", location = "") })
	public String submitTaskDoc() {
		if (document.getName() == null || document.getName().trim().equals("")) {
			this.addActionError("请正确填写文档名称");
			return ERROR;
		}
		if (document.getDocumentcode() == null
				|| document.getDocumentcode().trim().equals("")) {
			this.addActionError("请正确填写文档编码");
			return ERROR;
		}
		document.setOaTaskSubmit(oaTaskSubmit);
		this.getDocumentService().submitDocument(document);
		return SUCCESS;
	}

	public OaTask getOaTask() {
		return oaTask;
	}

	public void setOaTask(OaTask oaTask) {
		this.oaTask = oaTask;
	}

	public OaTaskService getOaTaskService() {
		return oaTaskService;
	}

	public void setOaTaskService(OaTaskService taskService) {
		this.oaTaskService = taskService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public Integer[] getIds() {
		return ids;
	}

	public void setIds(Integer[] ids) {
		this.ids = ids;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public OaTaskTypeService getOaTaskTypeService() {
		return oaTaskTypeService;
	}

	public void setOaTaskTypeService(OaTaskTypeService oaTaskTypeService) {
		this.oaTaskTypeService = oaTaskTypeService;
	}

	public OaTaskSourceService getOaTaskSourceService() {
		return oaTaskSourceService;
	}

	public void setOaTaskSourceService(OaTaskSourceService taskSourceService) {
		this.oaTaskSourceService = taskSourceService;
	}

	public List<OaTaskType> getOaTaskTypes() {
		return oaTaskTypes;
	}

	public void setOaTaskTypes(List<OaTaskType> taskTypes) {
		this.oaTaskTypes = taskTypes;
	}

	public List<OaTaskSource> getOaTaskSources() {
		return oaTaskSources;
	}

	public void setOaTaskSources(List<OaTaskSource> oaTaskSources) {
		this.oaTaskSources = oaTaskSources;
	}

	public void setPrincipals(String principals) {
		this.principals = principals;
	}

	public String getPrincipals() {
		return principals;
	}

	public void setOaTaskSubmitService(OaTaskSubmitService oaTaskSubmitService) {
		this.oaTaskSubmitService = oaTaskSubmitService;
	}

	public OaTaskSubmitService getOaTaskSubmitService() {
		return oaTaskSubmitService;
	}

	public void setOaTaskSubmit(OaTaskSubmit oaTaskSubmit) {
		this.oaTaskSubmit = oaTaskSubmit;
	}

	public OaTaskSubmit getOaTaskSubmit() {
		return oaTaskSubmit;
	}

	public void setOaTaskAuditService(OaTaskAuditService oaTaskAuditService) {
		this.oaTaskAuditService = oaTaskAuditService;
	}

	public OaTaskAuditService getOaTaskAuditService() {
		return oaTaskAuditService;
	}

	public void setOaTaskAudit(OaTaskAudit oaTaskAudit) {
		this.oaTaskAudit = oaTaskAudit;
	}

	public OaTaskAudit getOaTaskAudit() {
		return oaTaskAudit;
	}

	public void setCopyToPersons(String copyToPersons) {
		this.copyToPersons = copyToPersons;
	}

	public String getCopyToPersons() {
		return copyToPersons;
	}

	public void setOaTaskCritique(OaTaskCritique oaTaskCritique) {
		this.oaTaskCritique = oaTaskCritique;
	}

	public OaTaskCritique getOaTaskCritique() {
		return oaTaskCritique;
	}

	public void setOaTaskCritiqueService(
			OaTaskCritiqueService oaTaskCritiqueService) {
		this.oaTaskCritiqueService = oaTaskCritiqueService;
	}

	public OaTaskCritiqueService getOaTaskCritiqueService() {
		return oaTaskCritiqueService;
	}

	public void setOwnChildTasks(Collection<OaTask> ownChildTasks) {
		this.ownChildTasks = ownChildTasks;
	}

	public Collection<OaTask> getOwnChildTasks() {
		return ownChildTasks;
	}

	public void setNoticeService(NoticeService noticeService) {
		this.noticeService = noticeService;
	}

	public NoticeService getNoticeService() {
		return noticeService;
	}

	public String getLevelType() {
		return levelType;
	}

	public void setLevelType(String levelType) {
		this.levelType = levelType;
	}

	public void setOaTaskLog(OaTaskLog oaTaskLog) {
		this.oaTaskLog = oaTaskLog;
	}

	public OaTaskLog getOaTaskLog() {
		return oaTaskLog;
	}

	public void setOaTaskLogService(OaTaskLogService oaTaskLogService) {
		this.oaTaskLogService = oaTaskLogService;
	}

	public OaTaskLogService getOaTaskLogService() {
		return oaTaskLogService;
	}

	public void setOaTaskLogs(Collection<OaTaskLog> oaTaskLogs) {
		this.oaTaskLogs = oaTaskLogs;
	}

	public Collection<OaTaskLog> getOaTaskLogs() {
		return oaTaskLogs;
	}

	public void setDocument(Document document) {
		this.document = document;
	}

	public Document getDocument() {
		return document;
	}

	public void setDocumentService(DocumentService documentService) {
		this.documentService = documentService;
	}

	public DocumentService getDocumentService() {
		return documentService;
	}

	public void setSelectDoc(File selectDoc) {
		this.selectDoc = selectDoc;
	}

	public File getSelectDoc() {
		return selectDoc;
	}

	public void setSelectDocFileName(String selectDocFileName) {
		this.selectDocFileName = selectDocFileName;
	}

	public String getSelectDocFileName() {
		return selectDocFileName;
	}

	public void setDocIds(Integer[] docIds) {
		this.docIds = docIds;
	}

	public Integer[] getDocIds() {
		return docIds;
	}

	public void setDocLevels(Collection<DocLevel> docLevels) {
		this.docLevels = docLevels;
	}

	public Collection<DocLevel> getDocLevels() {
		return docLevels;
	}

	public void setDocLevelService(DocLevelService docLevelService) {
		this.docLevelService = docLevelService;
	}

	public DocLevelService getDocLevelService() {
		return docLevelService;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public Collection<Document> getRelatDocs() {
		return relatDocs;
	}

	public void setRelatDocs(Collection<Document> relatDocs) {
		this.relatDocs = relatDocs;
	}

	@SuppressWarnings("unchecked")
	public Collection<Document> getStorDocs() {
		return (Collection<Document>) this.getStorage().get(key);
	}

	public boolean isExistStor() {
		return existStor;
	}

	public void setExistStor(boolean existStor) {
		this.existStor = existStor;
	}

	public int getSubmitState() {
		return submitState;
	}

	public void setSubmitState(int submitState) {
		this.submitState = submitState;
	}

	public boolean isSubmited() {
		return submited;
	}

	public void setSubmited(boolean submited) {
		this.submited = submited;
	}

	public String[] getNames() {
		return names;
	}

	public void setNames(String[] names) {
		this.names = names;
	}

	public String[] getCodes() {
		return codes;
	}

	public void setCodes(String[] codes) {
		this.codes = codes;
	}

	public DocType[] getTypes() {
		return types;
	}

	public void setTypes(DocType[] types) {
		this.types = types;
	}

	public String[] getFiles() {
		return files;
	}

	public void setFiles(String[] files) {
		this.files = files;
	}

	public DocLevel[] getLevels() {
		return levels;
	}

	public void setLevels(DocLevel[] levels) {
		this.levels = levels;
	}

	public OaTaskKeyWordService getOaTaskKeyWordService() {
		return oaTaskKeyWordService;
	}

	public void setOaTaskKeyWordService(
			OaTaskKeyWordService oaTaskKeyWordService) {
		this.oaTaskKeyWordService = oaTaskKeyWordService;
	}

	public String[] getKeyWords() {
		return keyWords;
	}

	public void setKeyWords(String[] keyWords) {
		this.keyWords = keyWords;
	}

	public String[] getKeyNames() {
		return keyNames;
	}

	public void setKeyNames(String[] keyNames) {
		this.keyNames = keyNames;
	}

	public static String getKey() {
		return key;
	}

	public OaTaskKeyWord getOaTaskKeyWord() {
		return oaTaskKeyWord;
	}

	public void setOaTaskKeyWord(OaTaskKeyWord oaTaskKeyWord) {
		this.oaTaskKeyWord = oaTaskKeyWord;
	}

	public CodeCommon getCodeCommon() {
		return codeCommon;
	}

	public void setCodeCommon(CodeCommon codeCommon) {
		this.codeCommon = codeCommon;
	}

	public CodeCommonService getCodeCommonService() {
		return codeCommonService;
	}

	public void setCodeCommonService(CodeCommonService codeCommonService) {
		this.codeCommonService = codeCommonService;
	}

	public String getEncode() {
		return Encode;
	}

	public void setEncode(String encode) {
		Encode = encode;
	}

	public Code getCode() {
		return code;
	}

	public void setCode(Code code) {
		this.code = code;
	}

	public CodeService getCodeService() {
		return codeService;
	}

	public void setCodeService(CodeService codeService) {
		this.codeService = codeService;
	}

	public Collection<CodeCommon> getCodelist() {
		return codelist;
	}

	public void setCodelist(Collection<CodeCommon> codelist) {
		this.codelist = codelist;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public static String Increase(String backupNum) {
		String Inc = "";
		int lengths = backupNum.length();
		String lengthss = (Integer.parseInt(backupNum) + 1) + "";
		int increase = (lengthss.trim()).length();
		if (lengths != increase) {
			String In = "";
			for (int i = 0; i < lengths - increase; i++) {
				In = In + "0";
			}
			In = (In + lengthss).trim();
			Inc = In;
		} else {
			Inc = lengthss;
		}
		return Inc.trim();
	}

}
